<template>
  <div class="chat-view">
    <div class="chat-container">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h2>🤖 AI客服</h2>
          <p class="subtitle">24小时在线</p>
        </div>

        <div class="quick-actions">
          <el-button type="primary" @click="newConversation" size="default">
            新对话
          </el-button>
          <el-button @click="clearHistory" size="default">
            清除历史
          </el-button>
        </div>

        <div class="info-cards">
          <div class="info-card">
            <span class="icon">📊</span>
            <div>
              <p class="label">今日对话</p>
              <p class="value">{{ stats.todayChats }}</p>
            </div>
          </div>
          <div class="info-card">
            <span class="icon">⏱️</span>
            <div>
              <p class="label">平均响应</p>
              <p class="value">{{ stats.avgResponse }}s</p>
            </div>
          </div>
        </div>

        <div class="quick-questions">
          <h3>常见问题</h3>
          <button
            v-for="q in quickQuestions"
            :key="q"
            class="quick-question-btn"
            @click="sendQuickQuestion(q)"
          >
            {{ q }}
          </button>
        </div>
      </div>

      <!-- 主聊天区域 -->
      <div class="main-chat">
        <!-- 头部 -->
        <div class="chat-header">
          <div class="header-left">
            <div class="avatar">🤖</div>
            <div class="header-info">
              <h3>智能客服小智</h3>
              <p class="status">
                <span class="status-dot"></span>
                在线
              </p>
            </div>
          </div>
          <div class="header-right">
            <el-switch
              v-model="useRAG"
              active-text="知识库检索"
              inactive-text="直接对话"
            />
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="messages-container" ref="messagesContainer">
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-icon">👋</div>
            <h2>欢迎使用AI智能客服！</h2>
            <p>我可以帮您查询订单、商品、物流等信息</p>
          </div>

          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message', msg.role]"
          >
            <div class="avatar-small">
              {{ msg.role === 'user' ? '👤' : '🤖' }}
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">
                  {{ msg.role === 'user' ? '我' : '智能客服' }}
                </span>
                <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
              </div>
              <div class="message-text" v-html="renderMarkdown(extractTextContent(msg.content))"></div>
              
              <!-- 价格图表 -->
              <div v-if="extractChartData(msg.content)" class="inline-chart">
                <div :ref="el => setupChart(el, extractChartData(msg.content))" style="width: 100%; height: 300px;"></div>
              </div>
              
              <!-- 显示RAG检索结果 -->
              <div v-if="msg.retrievedDocs && msg.retrievedDocs.length > 0" class="rag-info">
                <details class="rag-details">
                  <summary>📚 参考知识库 ({{ msg.retrievedDocs.length }}条)</summary>
                  <div v-for="(doc, i) in msg.retrievedDocs" :key="i" class="doc-item">
                    <p class="doc-score">相关度: {{ (doc.relevance_score * 100).toFixed(0) }}%</p>
                    <p class="doc-content">{{ doc.content.substring(0, 100) }}...</p>
                  </div>
                </details>
              </div>

              <!-- Token统计 -->
              <div v-if="msg.tokens" class="message-meta">
                <span>🔢 Tokens: {{ msg.tokens.total }}</span>
                <span>💰 成本: ${{ msg.cost?.toFixed(4) }}</span>
                <span>⏱️ 耗时: {{ msg.duration?.toFixed(2) }}s</span>
              </div>
            </div>
          </div>

          <!-- 正在输入提示 -->
          <div v-if="isTyping" class="message assistant typing-indicator">
            <div class="avatar-small">🤖</div>
            <div class="message-content">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <textarea
            v-model="inputMessage"
            class="input-textarea"
            rows="3"
            placeholder="输入您的问题... (Enter发送，Shift+Enter换行)"
            @keydown.enter.exact.prevent="handleSend"
            @keydown.shift.enter="handleNewLine"
          ></textarea>
          <div class="input-actions">
            <span class="input-hint">Enter发送，Shift+Enter换行</span>
            <button
              class="send-button"
              :disabled="isSending || !inputMessage.trim()"
              @click="handleSend"
            >
              {{ isSending ? '发送中...' : '发送 📤' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import MarkdownIt from 'markdown-it'
import * as echarts from 'echarts'

// Markdown渲染器
const md = new MarkdownIt({
  html: false,
  linkify: true,
  typographer: true,
  breaks: true,
})

interface Message {
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  retrievedDocs?: any[]
  tokens?: any
  cost?: number
  duration?: number
}

// 响应式数据
const messages = ref<Message[]>([])
const inputMessage = ref('')
const isTyping = ref(false)
const isSending = ref(false)
const useRAG = ref(true)
const messagesContainer = ref<HTMLElement>()

// 会话ID管理已移除，现在使用用户登录token识别会话

const stats = reactive({
  todayChats: 0,
  avgResponse: 1.2,
})

const quickQuestions = [
  '我的订单在哪里？',
  '如何退换货？',
  '有什么优惠活动？',
  '商品什么时候发货？',
]

// 方法
const sendQuickQuestion = (question: string) => {
  inputMessage.value = question
  handleSend()
}

const handleNewLine = () => {
  inputMessage.value += '\n'
}

const handleSend = async () => {
  if (!inputMessage.value.trim() || isSending.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userMessage,
    timestamp: new Date(),
  })

  scrollToBottom()
  isTyping.value = true
  isSending.value = true

  try {
    // 获取token
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('请先登录')
    }
    
    // 调用API - 使用相对路径通过Vite代理，避免CORS问题
    const response = await fetch('/api/v1/chat/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,  // 使用token认证
      },
      body: JSON.stringify({
        message: userMessage,
        use_rag: useRAG.value,
        stream: false,
      }),
    })

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`)
    }

    const data = await response.json()

    // 添加AI回复
    messages.value.push({
      role: 'assistant',
      content: data.reply,
      timestamp: new Date(),
      retrievedDocs: data.retrieved_docs,
      tokens: data.tokens,
      cost: data.cost,
      duration: data.duration,
    })

    stats.todayChats++
    scrollToBottom()
  } catch (error: any) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败：' + (error.message || '未知错误'))
    
    // 添加错误消息
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我现在遇到了一些问题。请确保后端服务正常运行，或稍后再试。',
      timestamp: new Date(),
    })
  } finally {
    isTyping.value = false
    isSending.value = false
  }
}

const newConversation = () => {
  messages.value = []
  stats.todayChats = 0
  // 重新添加欢迎消息
  messages.value.push({
    role: 'assistant',
    content: '您好！我是智能客服小智，很高兴为您服务！😊\n\n我可以帮您：\n- 查询订单和物流信息\n- 解答商品相关问题\n- 处理退换货申请\n- 介绍优惠活动\n\n请问有什么可以帮您的吗？',
    timestamp: new Date(),
  })
  ElMessage.success('已开始新对话')
}

const clearHistory = () => {
  messages.value = []
  stats.todayChats = 0
  ElMessage.success('历史记录已清除')
}

const renderMarkdown = (content: string) => {
  return md.render(content)
}

const formatTime = (date: Date) => {
  if (!date) return ''
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  return date.toLocaleDateString('zh-CN')
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 提取文本内容（移除JSON图表数据部分）
const extractTextContent = (content: string) => {
  if (!content) return ''
  // 移除 ```json ... ``` 代码块
  return content.replace(/```json[\s\S]*?```/g, '').trim()
}

// 提取图表数据
const extractChartData = (content: string) => {
  if (!content) return null
  
  // 匹配 ```json ... ``` 代码块
  const match = content.match(/```json\s*([\s\S]*?)```/)
  if (!match) return null
  
  try {
    const data = JSON.parse(match[1])
    if (data.type === 'price_chart') {
      return data
    }
  } catch (e) {
    console.error('解析图表数据失败:', e)
  }
  
  return null
}

// 设置图表
const setupChart = (el: HTMLElement | null, chartData: any) => {
  if (!el || !chartData) return
  
  nextTick(() => {
    const chart = echarts.init(el)
    
    const dates = chartData.history.map((item: any) => {
      const date = new Date(item.date)
      return `${date.getMonth() + 1}/${date.getDate()}`
    })
    
    const prices = chartData.history.map((item: any) => item.price)
    
    const option = {
      title: {
        text: `${chartData.product_name} 价格走势`,
        left: 'center',
        textStyle: {
          fontSize: 16
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const item = params[0]
          return `${item.axisValue}<br/>价格: ¥${item.value}`
        }
      },
      grid: {
        left: '50px',
        right: '30px',
        top: '50px',
        bottom: '30px'
      },
      xAxis: {
        type: 'category',
        data: dates,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        name: '价格',
        type: 'line',
        data: prices,
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(64, 158, 255, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.05)'
            }]
          }
        }
      }]
    }
    
    chart.setOption(option)
    
    // 自适应窗口大小
    window.addEventListener('resize', () => {
      chart.resize()
    })
  })
}

onMounted(() => {
  // 加载欢迎消息
  messages.value.push({
    role: 'assistant',
    content: '您好！我是智能客服小智，很高兴为您服务！😊\n\n我可以帮您：\n- 查询订单和物流信息\n- 解答商品相关问题\n- 处理退换货申请\n- 介绍优惠活动\n\n请问有什么可以帮您的吗？',
    timestamp: new Date(),
  })
})
</script>

<style scoped>
.chat-view {
  height: 100vh;
  background: #f5f7fa;
  overflow: hidden;
}

.chat-container {
  height: 100%;
  display: flex;
  max-width: 1600px;
  margin: 0 auto;
}

/* 侧边栏样式 */
.sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow-y: auto;
}

.sidebar-header {
  text-align: center;
  margin-bottom: 24px;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.sidebar-header .subtitle {
  margin: 4px 0 0;
  color: #909399;
  font-size: 14px;
}

.quick-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

.info-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 20px;
}

.info-card {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-card .icon {
  font-size: 24px;
}

.info-card .label {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.info-card .value {
  margin: 2px 0 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.quick-questions h3 {
  font-size: 14px;
  color: #606266;
  margin: 0 0 12px;
}

.quick-question-btn {
  display: block;
  width: 100%;
  text-align: left;
  margin-bottom: 8px;
  padding: 10px 12px;
  font-size: 13px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s;
}

.quick-question-btn:hover {
  background: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

/* 主聊天区域 */
.main-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.header-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.header-info .status {
  margin: 4px 0 0;
  font-size: 12px;
  color: #67c23a;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #67c23a;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 消息列表 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #f5f7fa;
}

.welcome-message {
  text-align: center;
  padding: 60px 20px;
}

.welcome-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.welcome-message h2 {
  color: #303133;
  margin: 0 0 12px;
}

.welcome-message p {
  color: #909399;
  margin: 0;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.user {
  flex-direction: row-reverse;
}

.avatar-small {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.message.user .avatar-small {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.message-content {
  max-width: 70%;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message.user .message-content {
  background: #409eff;
  color: white;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.sender-name {
  font-weight: bold;
  font-size: 13px;
  color: #606266;
}

.message.user .sender-name {
  color: rgba(255, 255, 255, 0.9);
}

.message-time {
  font-size: 12px;
  color: #c0c4cc;
}

.message.user .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.message-text {
  line-height: 1.6;
  word-wrap: break-word;
}

.message-text :deep(p) {
  margin: 0.5em 0;
}

.message-text :deep(p:first-child) {
  margin-top: 0;
}

.message-text :deep(p:last-child) {
  margin-bottom: 0;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 0.5em 0;
  padding-left: 1.5em;
}

.inline-chart {
  margin-top: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.rag-info {
  margin-top: 12px;
}

.rag-details {
  font-size: 12px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 6px;
  padding: 8px;
}

.rag-details summary {
  cursor: pointer;
  font-weight: bold;
  color: #409eff;
  list-style: none;
  user-select: none;
}

.rag-details summary::-webkit-details-marker {
  display: none;
}

.doc-item {
  padding: 8px;
  background: white;
  border-radius: 4px;
  margin-top: 8px;
}

.doc-score {
  margin: 0 0 4px;
  color: #409eff;
  font-weight: bold;
}

.doc-content {
  margin: 0;
  color: #606266;
  line-height: 1.4;
}

.message-meta {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  font-size: 11px;
  color: rgba(0, 0, 0, 0.5);
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.message.user .message-meta {
  color: rgba(255, 255, 255, 0.7);
  border-top-color: rgba(255, 255, 255, 0.2);
}

.typing-indicator .typing-dots {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #c0c4cc;
  animation: typing 1.4s infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-8px);
    opacity: 1;
  }
}

/* 输入区域 */
.input-area {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  background: white;
}

.input-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: none;
  outline: none;
  transition: border-color 0.2s;
}

.input-textarea:focus {
  border-color: #409eff;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-hint {
  font-size: 12px;
  color: #c0c4cc;
}

.send-button {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-button:active:not(:disabled) {
  transform: translateY(0);
}

.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    display: none;
  }
  
  .message-content {
    max-width: 85%;
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar,
.sidebar::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track,
.sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb,
.sidebar::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover,
.sidebar::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>
